package com.cheneyjoo.filters;

import com.alibaba.fastjson.JSON;
import com.cheneyjoo.model.SYS_USER;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Optional;

public class GlobalFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Optional<Object> user = Optional.ofNullable(request.getSession().getAttribute("user"));
        if (user.isPresent()) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            Cookie[] cookies = request.getCookies();
            Optional<Cookie> cookie = Optional.ofNullable(cookies).isEmpty()? Optional.empty() : Arrays.stream(cookies).filter(s -> s.getName().equals("user")).findFirst();
            if (cookie.isPresent()) {
                String value = cookie.get().getValue();
                String decodeCookie = URLDecoder.decode(value,"utf-8");
                SYS_USER sessionUser = JSON.parseObject(decodeCookie, SYS_USER.class);
                HttpSession session = request.getSession();
                session.setAttribute("user", sessionUser);
                ((HttpServletResponse)servletResponse).sendRedirect(request.getContextPath() +"/ui/index.jsp");
            } else {
                if (request.getRequestURL().toString().endsWith("/login")) {
                    filterChain.doFilter(servletRequest, servletResponse);
                } else {
                    servletRequest.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
                }
            }

        }


    }

    @Override
    public void destroy() {

    }
}
